package com.emre.daoGenerator.bean;

import java.io.File;
import java.io.IOException;

import com.emre.daoGenerator.GlobalConstants;
import com.emre.daoGenerator.oracleObject.Field;
import com.emre.daoGenerator.utils.DataTypeMethodMapper;
import com.emre.daoGenerator.utils.JavaCodeWriter;
import com.emre.daoGenerator.utils.StringUtils;

public class BeanClassGenerator 
{
	private BeanDefinition beanDefinition;
	
	private String path;
	
	public BeanClassGenerator(BeanDefinition beanDefinition, String path)
	{
		this.beanDefinition = beanDefinition;
		this.path = path;
	}
	
	public File generate() throws IOException
	{
		JavaCodeWriter writer = new JavaCodeWriter(path + beanDefinition.getName() + ".java");
		
		String packageDeclaration = "package " + GlobalConstants.topLevelPackageName + "." +GlobalConstants.beanPackageName + ";";
		writer.write(packageDeclaration, 0);
		writer.writeEmptyLine();
		
		writer.write(GlobalConstants.beanClassImportStatements, 0);
				
		String classDeclaration = "public class " + beanDefinition.getName() + " implements Serializable";
		writer.write(classDeclaration, 0);
		writer.write("{", 0);
		
		for(Field field : beanDefinition.getFields())
		{
			String fieldDeclaration = "private " + DataTypeMethodMapper.mapOracleDataTypeToJavaType(field.getType()) + " " + field.getName() + ";";
			writer.write(fieldDeclaration, 1);
		}
		writer.writeEmptyLine();

		for(Field field : beanDefinition.getFields())
		{
			String javaTypeName = DataTypeMethodMapper.mapOracleDataTypeToJavaType(field.getType()); 
			
			String getterDeclaration = "public " + javaTypeName + " " + StringUtils.getterMethodName(field.getName()) + "() {";
			writer.write(getterDeclaration, 1);
			writer.write("return " + field.getName() + ";", 2);
			writer.write("}", 1);
			writer.writeEmptyLine();
			
			
			String setterDeclaration = "public " + javaTypeName + " " + StringUtils.setterMethodName(field.getName()) + "(" + javaTypeName + " " + field.getName() + ") {";
			writer.write(setterDeclaration, 1);
			writer.write("this." + field.getName() + " = " + field.getName() +";", 2);
			writer.write("}", 1);
			writer.writeEmptyLine();
		}
		
		writer.write("}", 0);
		
		writer.close();
		
		return writer.getFile();
	}
	
}
